package com.thread.consumeandproduct;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;

public class ProducerJetBlockQueue implements Runnable {

    private LinkedBlockingQueue<ProductJetBean> addReadyDataQueueList;

    private boolean flag = true;
    private ConsumerJetCom consumerJetCom;
    private boolean isExe = false;

    public ProducerJetBlockQueue(ConsumerJetCom consumerJetCom) {
        this.consumerJetCom = consumerJetCom;
        this.addReadyDataQueueList = new LinkedBlockingQueue<>();
    }

    public void receive(String content) {
        consumerJetCom.receive(content);
    }


    /**
     * 添加连续多个数据队列
     *
     * @param value
     */
    public void addMultiProduct(ProductJetBean value) {
        addReadyDataQueueList.offer(value);
    }

    public boolean isAllowSingle() {
        if (isExe || !addReadyDataQueueList.isEmpty()) {
            return false;
        }
        return true;
    }

    @Override
    public void run() {
        while (flag) {
            try {
                ProductJetBean value = addReadyDataQueueList.take();
                isExe = true;
                if (value != null) {
                    System.out.println("product:" + value.toString());
                    consumerJetCom.setProductBean(value);
                    ProductJetBean result = null;
                    for (int i = 0; i < value.getRepeatCount(); i++) {
                        Future<ProductJetBean> future = MCLJETMain.executorService.submit(consumerJetCom);
                        result = future.get();
                        if (result != null) {
                            System.out.println("consume:" + value.toString());
                            break;
                        } else {
                            System.out.println("consume:" + null);
                        }
                    }

                    if (result == null) {
                        if (value.getOnJetFinishListener() != null) {
                            value.getOnJetFinishListener().timeOut(value);
                        }
                    } else {
                        if (value.getOnJetFinishListener() != null) {
                            value.getOnJetFinishListener().finish(result);
                        }
                    }
                    isExe = false;
                }
            } catch (InterruptedException | ExecutionException e) {
                flag = false;
                isExe = false;
                System.out.println("InterruptedException run");
                e.printStackTrace();
            }
        }
    }

}
